﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
    public float movespeed=40f;
    public float rotatespd=100f;
    public Transform car;
    public bool isFire;
    // Start is called before the first frame update
    public List<GameObject> enemyList;//警戒范围内敌人列表引用
    private PlayerTankFind TowerObject;//旋转物体脚本
    private FireControlSystem fireControlSystemScript;//火控系统脚本

    private void Awake()
    {
        enemyList = new List<GameObject>();//申请内存
        //旋转功能脚本
        if (TowerObject == null)
            TowerObject = transform.Find("TankFree_Tower").GetComponent<PlayerTankFind>();
        //火控功能脚本
        if(fireControlSystemScript==null)
            fireControlSystemScript = transform.Find("TankFree_Tower").GetComponent<FireControlSystem>();
    }

    //触发器进入事件
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag.Equals("Enemy"))
            enemyList.Add(other.gameObject);//向列表中增加元素
    }

    //触发器离开事件
    private void OnTriggerExit(Collider other)
    {
        if (other.tag.Equals("Enemy"))
            enemyList.Remove(other.gameObject);//从列表中移除元素
    }

    void Start()
    {
        if(car==null)
            car=transform.Find("PlayerTank");
    }

    // Update is called once per frame
    void Update()
    {
        float translation = Input.GetAxis("Vertical") * movespeed * Time.deltaTime;
        car.Translate(Vector3.forward * translation);
        float rotation1 = Input.GetAxis("Horizontal") * 10000f * Time.deltaTime;
        car.Rotate(Vector3.up * Time.deltaTime * rotation1);
        //有敌人
        if(enemyList.Count>0)
            {
                if(TowerObject!=null)
                    TowerObject.isRun=true;//旋转
                //不瞄准就开火
                if(fireControlSystemScript!=null)
                    fireControlSystemScript.isRun=true;//火控开关：开
            }
        //没有敌人
        else
            {
                if(TowerObject!=null)
                    TowerObject.isRun=false;
                if(fireControlSystemScript!=null)
                    fireControlSystemScript.isRun=false;//火控开关：关
            }
    }
        public void CheckListNullElement()
    {
        StartCoroutine(ClearListNullElement());
    }

    //检查列表,移除空元素
    IEnumerator  ClearListNullElement()
    {
        yield return new WaitForSeconds(0.1f);
        for (int i = 0; i < enemyList.Count; i++)
        {
            if (enemyList[i] == null)
                enemyList.Remove(enemyList[i]);
        }
    }
}
